package com.dreammakerteam.frameworkdemo.base.controller;

import com.dreammakerteam.frameworkdemo.base.domain.RestResult;
import com.dreammakerteam.frameworkdemo.base.domain.DBaseException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


/**
 * Created by ty850 on 2017/7/16.
 */
@Controller
@RequestMapping
public class DSystemController {


    @RequestMapping("/admin")
    public Object admin () {
        return "admin/index";
    }

    @GetMapping("/admin/login")
    public Object toLoginPage() {
        return "admin/login";
    }

    @PostMapping("/admin/login")
    @ResponseBody
    public RestResult login(String username, String password) {
        RestResult r = new RestResult();
        //System.out.println(MessageFormat.format("{0}  ||  {1}", username, password));
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(username, password));
        } catch (Exception e) {
            r.setSuccess(false);
            r.setMsg("账号或密码错误");
        }
        return r;
    }

    @RequestMapping("/admin/logout")
    @ResponseBody
    public RestResult logout() {

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return null;
    }


    @RequestMapping("/file")
    public void getFile(String p, HttpServletResponse response) throws IOException {
        File file = new File(p);
        if (!file.exists())
            throw new DBaseException("文件不存在");

        ServletOutputStream out = response.getOutputStream();

        FileInputStream in = new FileInputStream(file);

        byte[] data = new byte[1024];
        int len;
        while((len = in.read(data)) > 0) {
            out.write(data, 0, len);
        }

        in.close();
        out.close();
    }


    @RequestMapping
    public String index() {
        return "qzhj/index";
    }


}
